package com.zlm.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author: 郑
 *
 */
public class UdpServerDemo {
    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接受数据
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        //阻塞接受
        socket.receive(packet);
        //输出
        System.out.println(packet.getAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));

        //建立数据包
        String msg = "你好啊";
        InetAddress localhost = InetAddress.getByName("localhost");
        DatagramPacket packet2 = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,9091);
        //发送
        socket.send(packet2);

        //关闭
        socket.close();
    }
}
